package com.jiuyin.dianjing.ui.fragment.homepage;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.HeadPhotoAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.HomepageMsgEvent;
import com.jiuyin.dianjing.model.TeamGameRecordsModel;
import com.jiuyin.dianjing.ui.activity.team.MyTeamsActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseRefreshLazyFragment;
import com.jiuyin.dianjing.util.LogUtil;
import com.lzy.okgo.cache.CacheMode;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETE_DATA_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_FANS_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAME_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NICK_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SIGNATURE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TEAM_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOPIC_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USERID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_TYPE0;
import static com.jiuyin.dianjing.api.enums.ApiEnum.APP_GET_USER_DETAIL_API;


/**
 * 主页（主页）
 */
public class HomepageFirst extends BaseRefreshLazyFragment<TeamGameRecordsModel> {
    @BindView(R.id.grid_members)
    RecyclerView gridMembers;

    @BindView(R.id.grid_often_games)
    RecyclerView gridGames;

    private HeadPhotoAdapter membersAdapter;
    private HeadPhotoAdapter gamesAdapter;
    private String mUserId = "";

    public HomepageFirst() {
        super(PAGE_NUM);
    }

    public static HomepageFirst newInstance(String userId) {
        HomepageFirst homepageFirst = new HomepageFirst();
        Bundle args = new Bundle();
        args.putString(KEY_USERID, userId);
        homepageFirst.setArguments(args);
        return homepageFirst;
    }

    @Override
    public void fetchData() {
        if (getArguments() != null) {
            mUserId = getArguments().getString(KEY_USERID);
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_USERID, mUserId);
        params.put(KEY_TYPE, VALUE_TYPE0);
        JSONObject jsonObject = new JSONObject(params);
        ServerApi.post(APP_GET_USER_DETAIL_API.getUrl(), jsonObject, CacheMode.REQUEST_FAILED_READ_CACHE, null, d -> addDisposable(d),
                new ApiResultCallback() {
                    @Override
                    public void onSuccess(JsonObject jsonObject) {
                        if (null != jsonObject) {
                            String attention_num = jsonObject.get(KEY_ATTENTION_NUM).getAsString();
                            String fans_num = jsonObject.get(KEY_FANS_NUM).getAsString();
                            String topic_num = jsonObject.get(KEY_TOPIC_NUM).getAsString();
                            String nickname = jsonObject.get(KEY_NICK_NAME).getAsString();
                            String id = jsonObject.get(KEY_ID).getAsString();
                            String sign = "";
                            if (jsonObject.has(KEY_SIGNATURE)) {
                                sign = jsonObject.get(KEY_SIGNATURE).getAsString();
                            }
                            HomepageMsgEvent homepageMsgEvent = new HomepageMsgEvent();
                            homepageMsgEvent.attention_num = attention_num;
                            homepageMsgEvent.fans_num = fans_num;
                            homepageMsgEvent.topic_num = topic_num;
                            homepageMsgEvent.id = id;
                            homepageMsgEvent.sign = sign;
                            homepageMsgEvent.nickname = nickname;
                            EventBus.getDefault().post(homepageMsgEvent);
                            LogUtil.log("HomepageFirst getUserDetail onSuccess = " + jsonObject.toString());
                            JsonArray jsonArray = jsonObject.getAsJsonArray(KEY_TEAM_LIST);
                            if (jsonArray != null) {
                                int size = jsonArray.size();
                                List<String> list = new ArrayList<>();
                                if (size > 0) {
                                    for (int i = 0; i < size; i++) {
                                        String object = jsonArray.get(i).getAsString();
                                        list.add(object);
                                    }
                                    updateMembers(list);
                                }
                            }
                            JsonArray jsonArray1 = jsonObject.getAsJsonArray(KEY_GAME_LIST);
                            if (jsonArray1 != null) {
                                int size = jsonArray.size();
                                List<String> list = new ArrayList<>();
                                if (size > 0) {
                                    for (int i = 0; i < size; i++) {
                                        String object = jsonArray1.get(i).getAsString();
                                        list.add(object);
                                    }
                                    updateGames(list);
                                }
                            }
                            List<TeamGameRecordsModel> competeList = new Gson().fromJson(jsonObject.getAsJsonArray(KEY_COMPETE_DATA_LIST), new TypeToken<List<TeamGameRecordsModel>>() {
                            }.getType());
                            dealWithSuccessInfo(competeList);
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        LogUtil.log("HomepageFirst"+msg);
                        dealOtherInfo();
                    }

                    @Override
                    public void onError(String msg) {
                        LogUtil.log(msg);
                        dealOtherInfo();
                    }
                });
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_homepage_first;
    }

    @Override
    protected void initData() {
        membersAdapter = new HeadPhotoAdapter(40f);
        gamesAdapter = new HeadPhotoAdapter(40f);
        gridMembers.setAdapter(membersAdapter);
        gridGames.setAdapter(gamesAdapter);
        gridMembers.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
        gridGames.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
    }

    @Override
    protected void initView() {
        mAdapter = new BaseRecyclerAdapter<TeamGameRecordsModel>(R.layout.item_team_game_records) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, TeamGameRecordsModel model, int position) {
                ImageView ivHead = holder.itemView.findViewById(R.id.img_game);
                Glide.with(getActivity())
                        .load(model.logo)
                        .override(ivHead.getWidth(), ivHead.getHeight())
                        .into(ivHead);
                holder.text(R.id.tv_match_title, model.name);
                holder.text(R.id.tv_match_status1, model.compet_num);
                holder.text(R.id.tv_match_status3, model.rank_num);
            }
        };
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        mRcvPage.addItemDecoration(divider);
        mRcvPage.setAdapter(mAdapter);
    }

    @OnClick({R.id.tv_all_members})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all_members:
                Bundle bundle = new Bundle();
                bundle.putString(KEY_TYPE, "2");
                bundle.putString(KEY_USERID, mUserId);
                goTargetActivity(MyTeamsActivity.class, bundle);
                break;
        }
    }

    /**
     * 战队成员
     *
     * @param list
     */
    private void updateMembers(List<String> list) {
        membersAdapter.setData(list);
    }

    /**
     * 常玩游戏
     *
     * @param list
     */
    private void updateGames(List<String> list) {
        gamesAdapter.setData(list);
    }
}
